package bean.managed;

import bean.managed.util.JsfUtil;
import bean.session.RightEntityFacade;
import bean.session.RoleEntityFacade;
import bean.session.SystemUserEntityFacade;
import entity.RightEntity;
import entity.RoleEntity;

import entity.SystemUserEntity;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import managedbean.AbstractBacking;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DualListModel;

@ManagedBean(name = "ArsController")
@SessionScoped
public class ArsController extends AbstractBacking implements Serializable {

    List<RightEntity> allRightsEntity = new ArrayList<RightEntity>();
    List<RightEntity> roleRightsEntity = new ArrayList<RightEntity>();
    List<String> allRightsString = new ArrayList<String>();
    List<String> roleRightsString = new ArrayList<String>();
    private DualListModel<String> rightsPickList;

    public List<RightEntity> getAllRightsEntity() {
        //List<RoleEntity> allRoles = new ArrayList<RoleEntity>();
        allRightsEntity = facade.findAllIncludeArchived();

        return allRightsEntity;
    }

    public Collection<RightEntity> getRoleRightsEntity() {
        //List<RoleEntity> allRoles = new ArrayList<RoleEntity>();
        roleRightsEntity = new ArrayList(getList());
        return roleRightsEntity;
    }

    public DualListModel<String> getRightsPickList() {
        if (rightsPickList == null) {
            //allRightsEntityList = new ArrayList<RightEntity>();

            roleRightsEntity = new ArrayList<RightEntity>(getRoleRightsEntity());
            //allRightsEntityList = ejbFacade.findAllIncludeArchived();
            for (int i = 0; i < getAllRightsEntity().size(); i++) {
                if (!roleRightsEntity.contains(allRightsEntity.get(i))) {
                    allRightsString.add(getAllRightsEntity().get(i).getRightName());
                }
            }

            //userRightsEntityList = new ArrayList<RightEntity>(getList());
            for (int i = 0; i < getRoleRightsEntity().size(); i++) {
                roleRightsString.add(roleRightsEntity.get(i).getRightName());
            }
            rightsPickList = new DualListModel<String>(allRightsString, roleRightsString);
            return rightsPickList;
        }
        return rightsPickList;
    }

    public void setRightsPickList(DualListModel<String> rolesPickList) {
        this.rightsPickList = rolesPickList;
    }

    public void updateRoleRights() {

        for (int i = 0; i < rightsPickList.getTarget().size(); i++) {
            //for (int j = 0; j < getList().size(); i++){
            String right =rightsPickList.getTarget().get(i);
            System.out.println(right+"du me may");
            if (getFacade().findRight(right) != null) {
                  System.out.println(right+"chamay");
                if (!getList().contains(getFacade().findRight(right))) {
                    getList().add(getFacade().findRight(right));
                     System.out.println("ngannnnnn");
                }
            }
            // }
        }
        List<RightEntity> allRightsInPickList = new ArrayList();
        for (int i = 0; i < rightsPickList.getTarget().size(); i++) {
            allRightsInPickList.add(getFacade().findRight(rightsPickList.getTarget().get(i)));
        }

        Iterator itr = getList().iterator();
        while (itr.hasNext()) {

            if (!allRightsInPickList.contains(itr.next())) {
                itr.remove();
            }
        }


        current.setRights(getList());
 current.modified(getLoginPerson());
        getEjbFacade().edit(current);
//          rightsPickList=null;
//          allRights.clear();
//          userRights.clear();
    }
    private Map<String, String> ARs;
    @ManagedProperty(value = "#{list}")
    private Collection<RightEntity> list;

    public Collection<RightEntity> getList() {
        return current.getRights();
    }

    public void setList(Collection<RightEntity> list) {
        this.list = list;
    }

    public Map<String, String> getARs() {
        List<RightEntity> list1 = new ArrayList<RightEntity>();
        list1 = facade.findAllIncludeArchived();
        ARs = new HashMap<String, String>();
        String[] k = new String[list1.size()];

        for (int i = 0; i < list1.size(); i++) {
            RightEntity r = list1.get(i);
            k[i] = r.getRightName();
            ARs.put(k[i], k[i]);
        }
        return ARs;
    }

    public void setARs(Map<String, String> ARs) {
        this.ARs = ARs;
    }
    private String status;
    private RoleEntity current;
    private RoleEntity selectedRole;

    public RoleEntity getSelectedRole() {
        return selectedRole;
    }

    public void setSelectedRole(RoleEntity selectedRole) {
        this.selectedRole = selectedRole;
    }
    private String result;
    private List<RightEntity> right;

    public List<RightEntity> getRight() {
        return right;
    }

    public void setRight(List<RightEntity> right) {
        this.right = right;
    }
    private List<RoleEntity> role;
    @EJB
    private bean.session.RoleEntityFacade ejbFacade;

    public RoleEntityFacade getEjbFacade() {
        return ejbFacade;
    }

    public void setEjbFacade(RoleEntityFacade ejbFacade) {
        this.ejbFacade = ejbFacade;
    }
    @EJB
    private bean.session.RightEntityFacade facade;

    public RightEntityFacade getFacade() {
        return facade;
    }

    public void setFacade(RightEntityFacade facade) {
        this.facade = facade;
    }
    @EJB
    private bean.session.SystemUserEntityFacade facade1;

    public SystemUserEntityFacade getFacade1() {
        return facade1;
    }

    public void setFacade1(SystemUserEntityFacade facade1) {
        this.facade1 = facade1;
    }
    private String[] sel;

    public String[] getSel() {
        return sel;
    }

    public void setSel(String[] sel) {
        this.sel = sel;
    }

    public ArsController() {
    }

    public RoleEntity getSelected() {

        if (current == null) {
            current = new RoleEntity();
        }
        return current;
    }

    public List<SystemUserEntity> getUserToBeModified(String roleName) {
        List<SystemUserEntity> sys = facade1.findAllIncludeArchived();
        List<SystemUserEntity> res = new ArrayList<SystemUserEntity>();
        for (SystemUserEntity s : sys) {
            if (testRole(s.getRoles(), roleName)) {
                res.add(s);
            }
        }
        return res;
    }

    public boolean testRole(Collection<RoleEntity> r, String name) {
        for (RoleEntity r1 : r) {
            if (r1.getRoleName().equalsIgnoreCase(name)) {
                return true;
            }
        }
        return false;
    }

    public String update() {
        try {
            List<SystemUserEntity> sys2 = getUserToBeModified(current.getRoleName());
//            Collection<RightEntity> rs= current.getRights();
//        
            Collection<RightEntity> result = getList();

            String[] lk = getSel();
            for (int i = 0; i < lk.length; i++) {
                boolean same = false;

                for (RightEntity r : result) {
                    // System.out.println(lk[i]+"hhhhh"+r.getRightName());
                    if (r.getRightName().equalsIgnoreCase(lk[i])) {
                        same = true;
                        break;
                    }

                }
                if (!same) {
                    System.out.println("lllll1 " + lk[i]);
                    RightEntity r1 = getFacade().findRight(lk[i]);
                    System.out.println("lllll");
                    current.getRights().add(r1);
                    for (SystemUserEntity s1 : sys2) {
                        s1.getRights().add(r1);
                        getFacade1().edit(s1);
                    }

                }

            }


            getEjbFacade().edit(current);

            System.out.println("yyyyyyyyyy");
            //Collection<SystemUserEntity> sys = facade1.findAllIncludeArchived();

//           for(SystemUserEntity s: sys){
//  
//                 
//             System.out.println(s.getName()+"xxxxxxxxx");
//             
//          
//             
//               s.getRights().addAll(current.getRights());getFacade1().edit(s);
//           }


            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RightsUpdated"));
            return "Right?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String remove() {
//        try {
        List<SystemUserEntity> sys2 = getUserToBeModified(current.getRoleName());
        Collection<RightEntity> result = getList();
        Collection<RightEntity> result1 = new ArrayList<RightEntity>();
        System.out.println("Roles Selected1111111111: " + current);
        for (RightEntity r : getList()) {
            System.out.println(r.getRightName() + "hhhhhhh ");
        }
        String[] lk = getSel();

        System.out.println(lk.length + "aaaaa");
        for (RightEntity r : result) {
            boolean have = false;

            for (int i = 0; i < lk.length; i++) {
                //check the list for existing rights

                System.out.println("bbbbbb1" + r.getRightName());
                System.out.println("cccccccc1" + lk[i]);
                if ((r.getRightName().equalsIgnoreCase(lk[i]))) {


                    have = true;
                    break;

                }
            }
            if (!have) {
                result1.add(r);


            } else {
                System.out.println(r.getRightName() + "zzzzzzzz");
                for (SystemUserEntity s1 : sys2) {


                    System.out.println(s1.getRights().remove(r) + "jjjjjjj");
                    getFacade1().edit(s1);

                    System.out.println(s1.getRights() + "wwwwwwwwww");
                }
            }
        }
        for (RightEntity r1 : result1) {
            System.out.println(r1.getRightName() + "mmmmmmm ");

        }


        current.setRights(result1);

        getEjbFacade().edit(current);

//            Collection<PersonEntity> user = current.getUsers();
//            for (PersonEntity p : user) {
//                if (p instanceof SystemUserEntity) {
//                    SystemUserEntity s = (SystemUserEntity) p;
//
//                    s.setRights(getRights());
//                    getFacade1().edit(s);
//                }
//            }
        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AccessRightRemoved"));
        return "Right?faces-redirect=true";
//        } catch (Exception e) {
//            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
//            return null;
//        }
    }

    public String roleSelect(SelectEvent event) {
        System.out.println("User Selected: " + selectedRole);
        System.out.println("" + (null == (RoleEntity) event.getObject()));
        current = selectedRole;
        setList(selectedRole.getRights());

        allRightsString.clear();
        roleRightsString.clear();
        roleRightsEntity.clear();
        allRightsEntity.clear();
        rightsPickList = null;
        return "Right?faces-redirect=true";
    }

    public List<RoleEntity> getRole() {
        role = new ArrayList<RoleEntity>();
        role = ejbFacade.findAllIncludeArchived();
        return role;
    }

    public void setRoles(ArrayList<RoleEntity> msg) {
        this.role = msg;
    }

    public List<RightEntity> getRights() {
        return (List<RightEntity>) current.getRights();
    }

    public void setRights(List<RightEntity> role) {
        current.setRights(role);
    }

    public RoleEntity getCurrent() {
        return current;
    }

    public void setCurrent(RoleEntity current) {
        this.current = current;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void statusUpdate(String status) {
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, new FacesMessage(status, null));
    }
}